<template>
    <div class="qilin-skill" id="currentPage">
        <QilinCard :cardConfig="{title:'插件库'}">
            <!-- <QilinDialog :dialogConfig="{isShow:true}"> -->
                <div>
                    <el-table :data="tableData" border>
                        <template v-for="(item, index)  in tableHeader">
                            <el-table-column :key="item.key" :label="item.label" :prop="item.key" 
                                align="center" show-overflow-tooltip :width="item.width">
                                <template slot-scope="scope" slot="header">
                                    <div class="mathjaxDom">
                                        {{ item.label }}
                                    </div>
                                </template>
                                <template slot-scope="scope">
                                    <div class="mathjaxDom">{{scope.row[item.key]}}</div>
                                </template>
                            </el-table-column>
                        </template>
                    </el-table>
                </div>
            <!-- </QilinDialog> -->
        </QilinCard>
        <QilinCard :cardConfig="{title:'功能库'}">
            <QilinWeb>
                <el-button size="mini" @click="exportPdf()">一键导出pdf</el-button>
                <el-button size="mini" @click="screenshot()">一键截图</el-button>
                <el-button size="mini" plain icon="el-icon-monitor" @click="previewOnlineFile()">预览线上文件</el-button>
                <el-button size="mini" plain icon="el-icon-view" @click="previewLocalFile()">预览本地文件</el-button>
            </QilinWeb>
            <QilinTable :tableConfig.sync="tableConfig" @changeCurrentPage="handleCurrentPage" @changeCurrentSize="handleSizeChange" id="table">
                <template v-slot:image="slotData">
                    <!-- <img :src="slotData.data.scope.row.image" style="width:100px;height:100px;"> -->
                    <el-image :src="uploadImageUrl+slotData.data.scope.row.image[0].fileName" style="width:100px;height:100px;" :preview-src-list="[uploadImageUrl+slotData.data.scope.row.image[0].fileName]" ref="previewImage"></el-image>
                </template>
            </QilinTable>
        </QilinCard>
        <QilinCard :cardConfig="{title:'演练库'}">
            <div id="container" style="height:200px;position:relative;">
                <el-button id="button" style="position:absolute;transition:none;" v-drag="dragOptions">el按钮拖拽</el-button>
                <!-- <i class="el-icon-question" style="font-size:24px;position:absolute;" v-drag="dragOptions"></i> -->
                <!-- <el-radio label="1" style="font-size:24px;position:absolute;" v-drag="dragOptions">备选项</el-radio> -->
                <button style="position:absolute;left:100px;margin-top:0px;" v-drag="dragOptions1">原生按钮拖拽</button>
            </div>
        </QilinCard>
        <QilinDialog :dialogConfig.sync="previewLocalConfig.dialogConfig" @handleClose="handleClosePreviewLocal">
            <el-upload action="#" :auto-upload="false" :on-change="changeFile" ref="previewUpload" :on-preview="onPreview">
                <el-button type="primary" size="mini">选择文件</el-button>
                <span slot="tip" style="margin-left:10px;">选择文件后可直接预览各种格式的文件</span>
            </el-upload>
            <div v-show="previewLocalConfig.previewLoading" style="width:100%;height:500px;overflow:auto;">正在加载中请稍后</div>
            <div v-show="!previewLocalConfig.previewLoading" ref="previewBox" style="width:100%;height:500px;overflow:auto;"></div>
        </QilinDialog>
        <QilinDialog :dialogConfig.sync="previewOnlineConfig.dialogConfig" @handleClose="handleClosePreviewOnline">
            <el-button size="mini" type="primary">预览word文档</el-button>
            <el-button size="mini" type="primary">预览pdf文档</el-button>
            <div v-show="previewOnlineConfig.previewLoading" style="width:100%;height:500px;overflow:auto;">正在加载中请稍后</div>
            <div v-show="!previewOnlineConfig.previewLoading" ref="previewBox" style="width:100%;height:500px;overflow:auto;"></div>
        </QilinDialog>
    </div>
</template>
<script>
import html2canvas from "html2canvas";
import { saveAs } from "file-saver";
import html2pdf from "html2pdf.js";

import QilinWeb from "@/components/QilinWeb.vue";
import QilinCard from "@/components/QilinCard.vue";

import { getImageData } from "@/api/message/index.js";

import { readBuffer, render } from "./previewUtil.js";

import {renderByMathjax} from 'mathjax-vue';


export default {
    inject: ["uploadImageUrl"],
    components: {
        QilinWeb,
        QilinCard,
    },
    data() {
        return {
            // 时间范围选择器只能选择同一年内的时间，不能跨年选择
            selectDate: null,
            pickerOptions: {
                //事件快捷选项设置
                disabledDate: (time) => {
                    if (this.selectDate == null) {
                        return false;
                    } else {
                        return (
                            this.selectDate.getFullYear() != time.getFullYear()
                        );
                    }
                },
                onPick: (date) => {
                    if (date.minDate && !date.maxDate) {
                        this.selectDate = date.minDate;
                    } else {
                        this.selectDate = null;
                    }
                },
            },
            tableConfig: {
                headerConfig: [
                    {
                        label: "序号",
                        type: "sortIndex",
                        width: 60,
                    },
                    {
                        label: "用户名",
                        prop: "name",
                        width: 200,
                    },
                    {
                        label: "邮箱",
                        prop: "email",
                        width: 200,
                    },
                    {
                        label: "图片",
                        prop: "image",
                        type: "slot",
                        slotName: "image",
                    },
                    {
                        label: "日期",
                        prop: "date",
                        width: 180,
                        type: "date",
                    },
                ],
                tableData: [],
                paginationsObj: {
                    currentPage: 1, //当前页
                    pageSize: 5, //当前每页数量
                    pageSizes: [5, 10, 15], //每页显示多少条选项集
                    total: 0, //表格总数量
                    layout: "total,sizes,prev,pager,next,jumper",
                },
            },
            dragOptions: {
                container: "#container",
                // $el:"#button",
                mode: "in",
                draggableX: true,
                draggableY: true,
                beforeDrag: (data) => {
                    // console.log("开始拖拽",data);
                },
                drag: (data) => {
                    // console.log(data);
                },
                dragged: (data) => {
                    // console.log("拖拽结束",data);
                },
                ready: (drag) => {
                    // console.log(drag);
                    // drag.dragTo(500,100);
                },
            },
            dragOptions1: {
                container: "#container",
                mode: "in",
                draggableX: true,
                draggableY: true,
                beforeDrag: (data) => {
                    // console.log("开始拖拽",data);
                },
                drag: (data) => {
                    // console.log(data);
                },
                dragged: (data) => {
                    // console.log("拖拽结束",data);
                },
                ready: (drag) => {
                    // console.log(drag);
                    drag.dragTo(200, 100).then((data) => {
                        // console.log("自动拖拽完毕",data);
                    });
                    // drag.draggableX=false;
                },
            },
            /**
             * 本地预览配置项
             */
            previewLocalConfig: {
                dialogConfig: {
                    //本地预览库弹窗配置项
                    isShow: false,
                    title: "本地预览",
                    width: "70%",
                },
                previewLoading: false, //是否正在加载
                lastRender: null, //上个渲染实例
            },
            /**
             * 线上预览配置项
             */
            previewOnlineConfig: {
                dialogConfig: {
                    //线上预览库弹窗配置项
                    isShow: false,
                    title: "线上预览",
                    width: "70%",
                },
                previewLoading: false, //是否正在加载
            },
            tableHeader: [
                {
                    key: "signal",
                    label: "待测信号",
                },
                {
                    key: "MD",
                    label: "m(div)",
                },
                {
                    key: "Dy",
                    label: `$\{D_y}(V/div)$`,
                },
                {
                    key: "ND",
                    label: "n(div)",
                },
                {
                    key: "Dt",
                    label: `$\{D_t}(s/div)$`,
                },
                {
                    key: "Vp",
                    label: `$\{V_p}=\{D_y}m(V)$`,
                },
                {
                    key: "T",
                    label: `$T=\{D_t}n(Hz)$`,
                },
                {
                    key:"Qilin",
                    width:250,
                    label:"公式"
                }
            ],
            tableData: [
                {
                    signal: "2V,50Hz",
                    MD: "1",
                    Dy: "2",
                    ND: "3",
                    Dt: "4",
                    Vp: "5",
                    T: "6",
                    Qilin:`$TE=\\sqrt{\\frac{1}{T-1}\\ast \\sum_{t=1}^{T}(R_{E,t}-\\bar{R}_{E})^{2}}$`
                },
                {
                    signal: "4V,1000Hz",
                    MD: "1",
                    Dy: "2",
                    ND: "3",
                    Dt: "4",
                    Vp: "5",
                    T: "6",
                    Qilin:"7"
                }
            ],
        };
    },
    methods: {
        // 点击一键导出pdf按钮事件监听
        exportPdf() {
            // 获取指定页面元素
            const pageElement = document.getElementById("currentPage");
            // 使用html2pdf将页面转换为pdf
            html2pdf()
                .set({
                    html2canvas: {
                        scale: 2,
                        width: document.getElementById("currentPage")
                            .clientWidth, //解决pdf图片不完整问题
                        useCORS: true, //解决图片不显示问题（解决图片跨域问题）
                    },
                    filename: "流程数据.pdf",
                    image: {
                        type: "jpeg",
                        quality: 0.98,
                    },
                    jsPDF: {
                        unit: "in",
                        format: "a4",
                        orientation: "portrait",
                    },
                    pagebreak: {
                        mode: "avoid-all", //处理pdf分页问题
                    },
                })
                .from(pageElement)
                .save("导出pdf.pdf"); //下载的文件名，可根据需求修改
        },
        // 点击一键截图按钮事件监听
        screenshot() {
            // 获取指定页面元素
            const pageElement = document.getElementById("currentPage");
            // 使用html2canvas将页面转换为图片
            html2canvas(pageElement, {
                useCORS: true,
            }).then((canvas) => {
                // 将canvas转换为blob对象
                canvas.toBlob((blob) => {
                    // 使用file-saver进行下载
                    saveAs(blob, "截图.png"); //下载的文件名，可根据需求修改
                });
            });
        },
        // 点击预览线上文件按钮事件监听
        previewOnlineFile() {
            this.previewOnlineConfig.dialogConfig.isShow = true;
        },
        // 点击关闭线上预览弹窗事件监听
        handleClosePreviewOnline() {
            this.previewOnlineConfig.dialogConfig.isShow = false;
        },
        // 点击预览本地文件按钮事件监听
        previewLocalFile() {
            this.previewLocalConfig.dialogConfig.isShow = true;
        },
        // 点击关闭本地预览弹窗事件监听
        handleClosePreviewLocal() {
            this.$refs["previewUpload"].clearFiles();
            this.$refs["previewBox"].innerHTML = "";
            this.previewLocalConfig.lastRender = null;
            this.previewLocalConfig.dialogConfig.isShow = false;
        },
        // 点击选择文件事件监听
        async changeFile(file, fileList) {
            // console.log(file,fileList);
            this.previewLocalConfig.previewLoading = true;
            try {
                const arrayBuffer = await readBuffer(file.raw);
                this.previewLocalConfig.previewLoading = false;
                this.previewLocalConfig.lastRender = await this.displayResult(
                    arrayBuffer,
                    file.raw
                );
            } catch (e) {
                console.log(e);
            } finally {
                this.previewLocalConfig.previewLoading = false;
            }
        },
        // 点击预览已上传的文件事件监听
        async onPreview(file) {
            this.previewLocalConfig.previewLoading = true;
            try {
                const arrayBuffer = await readBuffer(file.raw);
                this.previewLocalConfig.previewLoading = false;
                this.previewLocalConfig.lastRender = await this.displayResult(
                    arrayBuffer,
                    file.raw
                );
            } catch (e) {
                console.log(e);
            } finally {
                this.previewLocalConfig.previewLoading = false;
            }
        },
        // 渲染预览效果事件监听
        displayResult(buffer, file) {
            const { name } = file; //获取文件名
            const extendType = name.substr(name.lastIndexOf(".") + 1); //获取文件拓展名
            const { previewBox } = this.$refs; //获取输出DOM位置
            const newNode = document.createElement("div"); //生成新的DOM元素
            if (this.previewLocalConfig.lastRender) {
                //添加子元素，防止vue实例替换DOM元素
                // if(["txt","json","js","css","java","py","html","jsx","ts","tsx","xml","md","log","mp4","pptx"].includes(extendType)){
                //     // console.log(previewBox.children[0].children.length);
                //     previewBox.children[0].children.length !== 0 && previewBox.removeChild(this.previewLocalConfig.lastRender.$el);
                //     this.previewLocalConfig.lastRender.$destroy();
                // }else{
                previewBox.removeChild(this.previewLocalConfig.lastRender.$el);
                this.previewLocalConfig.lastRender.$destroy();
                // };
            }
            const childDom = previewBox.appendChild(newNode);
            return new Promise((resolve, reject) => {
                render(buffer, extendType, childDom)
                    .then(resolve)
                    .catch(reject);
            });
        },
        renderFormula() {
            this.$nextTick(() => {
                renderByMathjax(document.getElementsByClassName('mathjaxDom'))
            });
        },
        //点击切换页码事件监听
        handleCurrentPage(val) {
            // console.log(val);
            this.tableConfig.paginationsObj.currentPage = val;
            this.getTableData();
        },
        //点击切换每页数量事件监听
        handleSizeChange(val) {
            // console.log(val);
            this.tableConfig.paginationsObj.pageSize = val;
            this.getTableData();
        },
        // 初始化获取表格内数据
        getTableData() {
            getImageData({
                pageNum: this.tableConfig.paginationsObj.currentPage,
                pageSize: this.tableConfig.paginationsObj.pageSize,
            }).then((res) => {
                if (res.code === 1000) {
                    this.tableConfig.tableData = res.data.data;
                    this.tableConfig.paginationsObj.total = res.data.total;
                }
            });
        },
    },
    mounted() {
        this.getTableData();
        this.renderFormula();
    },
};
</script>
<style lang="less" scoped>
.qilin-skill {
    width: 100%;
    padding: 0 10px 40px;
}
</style>